/*
 * Sesame Inc.
 * Copyright (c) 2009 All Rights Reserved.
 */
package com.sesame.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.mvc.AbstractController;
import org.springframework.web.servlet.mvc.SimpleFormController;

import com.sesame.domain.Album;
import com.sesame.domain.Image;
import com.sesame.domain.User;
import com.sesame.service.AlbumService;
import com.sesame.service.ContactService;
import com.sesame.service.PageService;
import com.sesame.service.UserService;
import com.sesame.toolkit.Page;

/**
 * @author voidman
 * 
 */
public class ShowAlbumController extends AbstractController {

    private AlbumService albumService;
    private ContactService contactService;
    private PageService pageService;

    public void setPageService(PageService pageService) {
        this.pageService = pageService;
    }

    public void setAlbumService(AlbumService albumService) {
        this.albumService = albumService;
    }

    public void setContactService(ContactService contactService) {
        this.contactService = contactService;
    }

    protected ModelAndView handleRequestInternal(HttpServletRequest request,
            HttpServletResponse response) throws Exception {

        Integer user1Id = (Integer) request.getSession().getAttribute("userId");
        Integer albumId = Integer.parseInt(request.getParameter("albumId"));

        // 分页相关
        String currentPage = request.getParameter("page");
        Page page = pageService.paging(request, currentPage);
        page.setRecordCount(albumService.getImageCount(albumId));
        page.setId(albumId);

        Album album = albumService.showAlbum(albumId);
        Integer user2Id = album.getUserId();

        if (user1Id != null) {
            if (user1Id.intValue() != user2Id.intValue()) {
                boolean isFriend = contactService.isFriend(user2Id, user1Id);
                if (album.getPrivacy().equals("2")
                        || (!isFriend && album.getPrivacy().equals("1"))) {
                    return new ModelAndView("redirect:error.html");
                }
            }
        } else {
            if (album.getPrivacy().equals("2")
                    || (album.getPrivacy().equals("1"))) {
                return new ModelAndView("redirect:error.html");
            }
        }

        List<Image> imageList = albumService.listImage(page);
        Map model = new HashMap();
        model.put("album", album);
        model.put("imageList", imageList);
        model.put("page", page);

        return new ModelAndView("showAlbum", model);
    }

}